<?php

namespace App\Http\Controllers;

use App\Models\GrCoupon;
use App\Models\GrUser;
use App\Models\GrUserCoupons;
use App\service\JwtService;
use App\service\ReturnService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use SebastianBergmann\Diff\Exception;

class Coupon extends Controller
{
    /**
     * 优惠券可兑换列表
     * @param Request $request
     */
    public function couponExchangeList(Request $request): \Illuminate\Http\JsonResponse
    {
        //查询可兑换优惠券的信息
        $CouponData = GrCoupon::where('coupon_state', 0)->where('coupon_distribution_method', 2)->paginate(5);
        if ($CouponData) {
            return ReturnService::successReturn(200, '获取成功', $CouponData);
        }
        return ReturnService::failedReturn(500, '获取失败', '');
    }

    /**
     * 优惠券兑换
     * @param Request $request
     */
    public function couponExchange(Request $request): \Illuminate\Http\JsonResponse
    {
        $coupon_id = $request->post('coupon_id');
        $token = $request->header('token');
        $user = JwtService::decodeToken($token);//解析token获取用户id
        $user_id = $user->data->id;
        $exchangeData = GrCoupon::where('coupon_id', $coupon_id)->first();
        $exchangeNumber = $exchangeData->exchange_integral_number;
        $couponExchangeNumber = Redis::get('coupon_exchange_number' . $user_id . $coupon_id);//取出购买的证明
        if ($couponExchangeNumber) {//如未取出则视为为兑换过
            return ReturnService::failedReturn(500, '兑换次数已上限');
        }
        $integral = GrUser::where('id', $user_id)->pluck('integral');
        if (!$integral) {
            return ReturnService::failedReturn(500, '获取失败');
        }
        $userIntegral = ($integral->toArray())[0];//取出用户的剩余积分
        if ($userIntegral < $exchangeNumber) {
            return ReturnService::failedReturn(500, '积分不足');
        }
        try {
            DB::beginTransaction();//开始事务
            GrUser::where('id', $user_id)->update(['integral' => $userIntegral - $exchangeNumber]);//修改用户积分
            $couponData = GrCoupon::where('coupon_id', $coupon_id)->pluck('coupon_stock');
            $stock = $couponData[0];
            GrCoupon::where('coupon_id', $coupon_id)->update(['coupon_stock' => $stock - 1]);
            GrUserCoupons::create(['coupon_id' => $coupon_id, 'coupon_source' => 1, 'user_id' => $user_id]);//添加优惠券给用户
            //存储已经兑换记录
            $couponData = [
                'couponID' => $coupon_id,//领取的优惠券
                'userID' => $user_id,//领取者
                'receiveTime' => time(),//领取的时间
                'couponSource' => 1//优惠券来源
            ];
            Redis::setex('coupon_exchange_number' . $user_id . $coupon_id, time() + 86400 * $exchangeData->coupon_effective_day, time());
            Redis::set('couponReceiveRecord' . $user_id, json_encode($couponData));
        } catch (Exception $exception) {
            DB::rollBack();//回滚
            return ReturnService::failedReturn(500, '兑换失败');
        }
        DB::commit();
        return ReturnService::successReturn(200, '兑换成功', '');
    }

}
